package com.itheima.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter")
@Slf4j
public class LoginCheckFilter implements Filter {
    private String[] authUrl = new String[]{
            "/employee/login",
            "/employee/logout",
            "/backend/**",
            "/front/**"
    };

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //拦截所有请求
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String uri = request.getRequestURI();
        log.info("[过滤器。。。。],uri:{}", request.getRequestURI());

        //确定哪些URI放行。登录页面，静态资源
        //判断本次请求是否处理  判断URI是否拦截
        boolean isAuth = checkURI(uri);

        //不需要处理，放行
        if (isAuth) {
            log.info("允许放行");
            filterChain.doFilter(request, response);
            return;
        }

        //需要处理
        if (request.getSession().getAttribute("employee") != null) {
            log.info("[登录检查]，已登录，允许通过",request.getSession().getAttribute("employee"));

            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request, response);
            return;
        }


        //未登录，返回登录的错误信息
        String name = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(name);
        //如果没问题 放行
        //filterChain.doFilter(request, response);
    }

    private boolean checkURI(String reqUri) {
        //匹配通配符
        AntPathMatcher pathMatcher = new AntPathMatcher();
        //这里处理逻辑
        for (String url : authUrl) {
            if (pathMatcher.match(url, reqUri)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
}
